
import 'package:async_button/async_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/account/iview/account_summary_iview.dart';
import 'package:flutter_deer/account/models/account_summary_entity.dart';
import 'package:flutter_deer/account/presenter/account_summary_presenter.dart';
import 'package:flutter_deer/index/index_router.dart';
import 'package:flutter_deer/index/iview/game_group_detail_iview.dart';
import 'package:flutter_deer/index/models/football_ratio_entity.dart';
import 'package:flutter_deer/index/presenter/game_group_detail_presenter.dart';
import 'package:flutter_deer/index/provider/game_group_detail_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/widgets/my_scroll_view.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_deer/widgets/text_label_item.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';
import 'package:text_scroll/text_scroll.dart';
import "package:intl/intl.dart" as nf;

class GameGroupDetailPage extends StatefulWidget {

  const GameGroupDetailPage({
    super.key,
    this.groupId
  });

  final String? groupId;

  @override
  _GameGroupDetailPageState createState() => _GameGroupDetailPageState();
}

class _GameGroupDetailPageState extends State<GameGroupDetailPage> with BasePageMixin<GameGroupDetailPage, PowerPresenter>, AutomaticKeepAliveClientMixin<GameGroupDetailPage> implements GameGroupDetailIMvpView,AccountSummaryIMvpView {
  @override
  bool get wantKeepAlive => false;
  final _list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0];
  String _orderAmountStr = '';
  late GameGroupDetailPagePresenter gameGroupDetailPagePresenter;
  late AccountSummaryPagePresenter accountSummaryPagePresenter;
  GameGroupDetailPageProvider provider = GameGroupDetailPageProvider();
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    gameGroupDetailPagePresenter = new GameGroupDetailPagePresenter();
    accountSummaryPagePresenter = new AccountSummaryPagePresenter();
    powerPresenter.requestPresenter([gameGroupDetailPagePresenter,accountSummaryPagePresenter]);
    return powerPresenter;
  }
  StateType? accountInfoStateType = StateType.loading;

  @override
  void initState() {
    super.initState();
    gameGroupDetailPagePresenter.fetchGroupDetail(widget.groupId);
    accountSummaryPagePresenter.getAccountSummary();
    provider.setLoading(true);
  }

  @override
  void dispose() {
    provider.dispose();
    super.dispose();
  }

  @override
  void setAccountSummary(AccountSummaryEntity? entity){
    provider.setAccountSummary(entity);
    setState(() {
      accountInfoStateType = StateType.empty;
    });
  }

  @override
  void setFootballRatioGroup(FootballRatioGroupEntity? groupEntity){
    provider.setGroupEntity(groupEntity);
  }

  @override
  void setResidueGiveScore(double? residueGiveScore){
    provider.setResidueGiveScore(residueGiveScore);
  }

  @override
  void setBettingResult(String? result){
    provider.setBettingResult(result);
    accountSummaryPagePresenter.getAccountSummary();
    if(result!='0') {
      showToast('${DeerLocalizations.of(context)!.confirmation.nullSafe}');
      Navigator.of(context).pop();
      // gameGroupDetailPagePresenter.fetchGroupDetail(widget.groupId);
      NavigatorUtils.push(context, IndexRouter.bettingDetailPage,arguments: result);
    }else{
      showToast('${DeerLocalizations.of(context)!.submitFail.nullSafe}');
    }
  }

  void _createOrder() {
    FootballRatioGroupEntity? groupEntity = provider.groupEntity;
    gameGroupDetailPagePresenter.saveBetting(groupEntity!.groupId.nullSafe, '1', '2', '1', provider.orderAmount);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<GameGroupDetailPageProvider>(
        create: (_) => provider,
        child: Consumer<GameGroupDetailPageProvider>(
          builder: (_,provider,child){
            if(provider.loading==true){
              return Scaffold(
                  appBar: MyAppBar(
                    centerTitle: '${DeerLocalizations.of(context)!.dataLoading.nullSafe}'
                  )
              );
            }else {
              FootballRatioGroupEntity? groupEntity = provider.groupEntity;
              return Scaffold(
                appBar: MyAppBar(
                    centerTitle: groupEntity?.title.nullSafe ?? ''
                ),
                body: MyScrollView(
                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                  bottomButton: Padding(
                    padding: const EdgeInsets.only(
                        left: 16.0, right: 16.0, bottom: 8.0),
                    child: MyButton(
                      onPressed: (){_showCustomModalBottomSheet(provider);},
                      text: '${DeerLocalizations.of(context)!.placeAnOrder.nullSafe}',
                    ),
                  ),
                  children: groupEntity==null?[]:_buildBody(context,groupEntity),
                ),

                /// 同时存在底部按钮与keyboardConfig配置时，为保证Android与iOS平台软键盘弹出高度正常，添加下面的代码。
                resizeToAvoidBottomInset: defaultTargetPlatform !=
                    TargetPlatform.iOS,
              );
            }
          }
        ),
    );
  }

  Future<dynamic> _showCustomModalBottomSheet(GameGroupDetailPageProvider provider) async {
    showModalBottomSheet<void>(
      backgroundColor: context.isDark?Colours.dark_bg_color:Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState){
            return BottomSheet(onClosing: (){}, builder: (BuildContext context){
              return Container(
                  clipBehavior: Clip.antiAlias,
                  decoration: BoxDecoration(
                    color: context.isDark?Colours.dark_bg_color:Colors.transparent,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.0),
                      topRight: Radius.circular(20.0),
                    ),
                  ),
                  height: MediaQuery.of(context).size.height / 2.0+200,
                  child: MyScrollView(
                    bottomButton: Padding(
                      padding: EdgeInsets.only(
                          left: 0.0, right: 0.0, bottom: 0.0),
                      child: Container(
                        color: Theme.of(context).dividerTheme.color,
                        child: GridView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 3,
                              childAspectRatio: 1.953,
                              mainAxisSpacing: 0.6,
                              crossAxisSpacing: 0.6,
                            ),
                            itemCount: 12,
                            itemBuilder: (_, index) => _buildButton(index,provider,setState)
                        ),
                      ),
                      // child: MyButton(
                      //   onPressed: () => _createOrder(),
                      //   text: '${DeerLocalizations.of(context)!.submit.nullSafe}',
                      // ),
                    ),
                    children: [
                      SizedBox(
                        height: 50,
                        child: Stack(
                          textDirection: TextDirection.rtl,
                          children: [
                            Center(
                              child: Text(
                                '${DeerLocalizations.of(context)!.placeAnOrder.nullSafe}',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 16.0),
                              ),
                            ),
                            IconButton(
                                icon: Icon(Icons.close),
                                onPressed: () {
                                  Navigator.of(context).pop();
                                }),
                          ],
                        ),
                      ),
                      Divider(height: 1.0),
                      TextLabelItem(
                        title: '${DeerLocalizations.of(context)!.allowBettingAmount.nullSafe}',
                        hintText: provider!.accountSummaryStateType==StateType.loading?'${DeerLocalizations.of(context)!.dataLoading.nullSafe}':nf.NumberFormat.decimalPattern('en_us').format(provider.accountSummaryData!.allowPositiveWaveBettingScore).toString(),
                      ),
                      TextLabelItem(title: '${DeerLocalizations.of(context)!.odds.nullSafe}${provider.groupEntity!.groupRatio!.toString()}',hintText: provider.willPrizeAmount==0?'${DeerLocalizations.of(context)!.willPrizeAmount.nullSafe}':'${nf.NumberFormat.decimalPattern('en_us').format(provider.willPrizeAmount).toString()}',actionText: '${DeerLocalizations.of(context)!.calculate.nullSafe}',onPressed: (AsyncBtnStatesController btnController){
                        btnController.update(AsyncBtnState.success);
                      },),
                      TextLabelItem(
                        title: '${DeerLocalizations.of(context)!.orderAmount.nullSafe}',
                        hintText: _orderAmountStr.trim()==''?'${DeerLocalizations.of(context)!.inputOrderAmount.nullSafe}':_orderAmountStr.nullSafe,
                      )
                    ],
                  )
              );
            });
          },
        );
      }
    ).then((value) => {
      provider.resetOrderAmmountStr().then((value) => setState(()=>{
      _orderAmountStr = provider.orderAmountStr.nullSafe
      }))
    });
  }

  List<Widget> _buildBody(BuildContext context,FootballRatioGroupEntity? groupEntity) {
    List<FootballRatioEntity>? ratios = groupEntity?.ratios;
    List<Widget> list = [];
    for(int i=0;i<ratios!.length;i++){
      FootballRatioEntity ratioEntity = ratios[i];
      FootballGameEntity? gameEntity = ratioEntity.game;
      String? outcome = ratioEntity.outcome.nullSafe;
      String? outcomeName = '';
      if(outcome=='1'){
        outcomeName = '${DeerLocalizations.of(context)!.win.nullSafe}';
      }else if(outcome=='2'){
        outcomeName = '${DeerLocalizations.of(context)!.flat.nullSafe}';
      }else if(outcome=='3'){
        outcomeName = '${DeerLocalizations.of(context)!.negative.nullSafe}';
      }else if(outcome=='4'){
        outcomeName = '${DeerLocalizations.of(context)!.letWin.nullSafe}';
      }else if(outcome=='5'){
        outcomeName = '${DeerLocalizations.of(context)!.letFlat.nullSafe}';
      }else if(outcome=='6'){
        outcomeName = '${DeerLocalizations.of(context)!.letNegative.nullSafe}';
      }else if(outcome=='7'){
        outcomeName = '${DeerLocalizations.of(context)!.letTransferFlat.nullSafe}';
      }
      MyCard card = MyCard(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 5),
          child: Column(
            children: [
              SizedBox(height: 5,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(ratioEntity.gameName.nullSafe),
                  Text(gameEntity!.playDate.nullSafe.substring(5)+' '+gameEntity!.playTime.nullSafe)
                ],
              ),
              SizedBox(height: 5,),
              Divider(height: 1.0,indent: 0.0),
              SizedBox(height: 5,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: (MediaQuery.of(context).size.width-80)/2,
                    child: Column(
                      children: [
                        Image(image:ImageUtils.getImageProvider(Constant.imageServerHost+'${gameEntity.teamOne!.image}',holderImg: 'shop/tx'),width: 30,height: 30,),
                        SizedBox(height: 12,),
                        TextScroll(gameEntity.teamOne!.name.nullSafe,mode: TextScrollMode.endless,pauseBetween: Duration(milliseconds: 500),)
                      ],
                    ),
                  ),
                  LoadAssetImage('logo',format:ImageFormat.gif,width:50,height:50),
                  Container(
                    width: (MediaQuery.of(context).size.width-80)/2,
                    child: Column(
                      children: [
                        Image(image:ImageUtils.getImageProvider(Constant.imageServerHost+'${gameEntity.teamTwo!.image}',holderImg: 'shop/tx'),width: 30,height: 30,),
                        SizedBox(height: 12,),
                        TextScroll(gameEntity.teamTwo!.name.nullSafe,mode: TextScrollMode.endless,pauseBetween: Duration(milliseconds: 500),)
                      ],
                    )
                  )
                ],
              ),
              SizedBox(height: 5,),
              Divider(height: 1.0,indent: 0.0),
              SizedBox(height: 5,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(outcomeName.nullSafe),
                  Text(ratioEntity.odds.toString()??'')
                ],
              ),
              SizedBox(height: 5,)
            ],
          ),
        )
      );
      Padding padding = Padding(padding: EdgeInsets.symmetric(horizontal: 10.0,vertical: 5),child: card,);
      list.add(padding);
    }
    return list;
  }

  Widget _buildButton(int index,GameGroupDetailPageProvider provider,setState) {
    final color = context.isDark ? Colours.dark_bg_gray : Colours.dark_button_text;
    return Material(
      color: (index == 9 || index == 11) ? color : null,
      child: InkWell(
        child: Center(
          child: index == 9 ? Semantics(
            label: '${DeerLocalizations.of(context)!.delete.nullSafe}',
            child: LoadAssetImage('account/del', width: 32.0),
          ) : index == 11 ? Semantics(
            label: '${DeerLocalizations.of(context)!.ok.nullSafe}',
            child: Text('${DeerLocalizations.of(context)!.ok.nullSafe}'),
          ) : Text(
            _list[index].toString(),
            style: TextStyle(fontSize: 26.0),
          ),
        ),
        onTap: () async {
          if (index == 11) {
            if(_orderAmountStr.trim().nullSafe==''){
              showToast('${DeerLocalizations.of(context)!.inputOrderAmount.nullSafe}');
              return;
            }else{
              _createOrder();
              return;
            }
          }

          if (index == 9) {
            provider.deleteOrderAmountStrByLast().then((value) => {
              setState((){
                _orderAmountStr = provider.orderAmountStr.nullSafe==''?'':nf.NumberFormat.decimalPattern('en_us').format(double.parse(provider.orderAmountStr.nullSafe));
              })
            });
            setState(() {

            });
            return;
          }
          provider.appendOrderAmountStr(_list[index].toString()).then((value) => {
            setState((){
              _orderAmountStr = provider.orderAmountStr.nullSafe==''?'':nf.NumberFormat.decimalPattern('en_us').format(double.parse(provider.orderAmountStr.nullSafe));
            })
          });
        },
      ),
    );
  }

}